package com.frinder.hadoop.job.joiner;

import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

/**
 * @author frinder
 * @date 2018/6/26
 * @Description: 运行 job
 */
@Slf4j
public class JoinerJob {

    public void run(String[] args) throws Exception {
        Configuration conf = new Configuration();
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        Job job = Job.getInstance(conf, "joiner_dept_info_job");
        job.setJarByClass(JoinerJob.class);
        job.setMapOutputKeyClass(TextPair.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.setPartitionerClass(KeyPartitioner.class);
        /**
         * 一个 group一个 Iterable因此，一个 group中所有元素 key都是compare==0
         */
        job.setGroupingComparatorClass(TextPair.FirstComparator.class);
        // 入/出 path
        String deptNamePathStr = otherArgs[0];
        String deptStrengthPathStr = otherArgs[1];
        String outputPathStr = otherArgs[2];
        log.info("deptNamePathStr:{} deptStrengthPathStr: {}, outputPathStr: {}",
                deptNamePathStr,
                deptStrengthPathStr,
                outputPathStr
        );
        // mapper设置
        MultipleInputs.addInputPath(job, new Path(deptNamePathStr), TextInputFormat.class, DeptNameMapper.class);
        MultipleInputs.addInputPath(job, new Path(deptStrengthPathStr), TextInputFormat.class, DeptStrengthMapper.class);
        // reducer设置
        job.setReducerClass(DeptReducer.class);
        // 删除 out目录
        Path outputPath = new Path(outputPathStr);
        FileSystem fileSystem = outputPath.getFileSystem(conf);
        if (fileSystem.exists(outputPath)) {
            log.info("Output: {} exists, delete it !", outputPathStr);
            fileSystem.delete(outputPath, true);
        }
        FileOutputFormat.setOutputPath(job, new Path(outputPathStr));

        boolean result = job.waitForCompletion(true);
        log.info("Result: {}", result);
    }

    /**
     * Partitioner组件可以让Map对Key进行分区，从而可以根据不同的key来分发到不同的reduce中去处理
     */
    public static class KeyPartitioner extends Partitioner<TextPair, Text> {
        @Override
        public int getPartition(TextPair key, Text value, int numPartitions) {
            int result = (key.getFirst().hashCode() & Integer.MAX_VALUE) % numPartitions;
            log.info("*** getPartition: {}", result);
            return result;
        }
    }

}
